package com.storage.system.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.storage.common.core.domain.AjaxResult;
import com.storage.common.core.domain.ServiceResponse;
import com.storage.common.core.page.TableDataInfo;
import com.storage.common.enums.OwnerType;
import com.storage.common.enums.ProductStatusType;
import com.storage.common.enums.RoleType;
import com.storage.common.utils.GsonUtil;
import com.storage.common.utils.NumerUtils;
import com.storage.common.utils.StringUtils;
import com.storage.system.domain.*;
import com.storage.system.mapper.*;
import com.storage.system.service.IStorageProductService;
import com.storage.system.utils.GoodsConvertUtils;
import com.storage.system.vo.ShopStorageDetail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 产品 服务层实现
 *
 * @author ruoyi
 * @date 2019-08-26
 */
@Service
public class StorageProductServiceImpl implements IStorageProductService {

    private static final Logger logger = LoggerFactory.getLogger(StorageProductServiceImpl.class);

    @Autowired
    private StorageProductMapper storageProductMapper;

    @Autowired
    private StorageGoodsMapper storageGoodsMapper;

    @Autowired
    private StorageImageMapper storageImageMapper;

    @Autowired
    private StorageUserAgentMapper storageUserAgentMapper;

    @Autowired
    private StorageShopMapper storageShopMapper;

    @Autowired
    private StorageShopOrderMapper storageShopOrderMapper;

    /**
     * 查询产品信息
     *
     * @param id 产品ID
     * @return 产品信息
     */
    @Override
    public StorageProduct selectStorageProductById(Long id) {
        return storageProductMapper.selectStorageProductById(id);
    }

    /**
     * 查询产品列表
     *
     * @param storageProduct 产品信息
     * @return 产品集合
     */
    @Override
    public ServiceResponse<TableDataInfo> selectStorageProductList(StorageUser currentUser, StorageProduct storageProduct, Integer pageNum, Integer pageSize) {

        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSize == null) {
            pageSize = 10;
        }
        
        if (storageProduct.getClient() && org.apache.commons.lang3.StringUtils.isNotBlank(storageProduct.getClientBrands())) {
            List<String> clientBrands = Arrays.asList(storageProduct.getClientBrands().split(","));
            storageProduct.setClientBrandsList(clientBrands);
        }
        Long canOperationId = RoleType.getOperationUserId(currentUser.getRole(), currentUser.getId(), currentUser.getShopId());
        if (storageProduct.getCreateUserId() == null) {
            // 代理商 || 店铺 才有产品列表
            storageProduct.setCreateUserId(canOperationId);
            storageProduct.setOwnerType(RoleType.getOwnerType(currentUser.getRole()));
        } else if (storageProduct.getCreateUserId() != null && canOperationId.intValue() != storageProduct.getCreateUserId()) {
            storageProduct.setOwnerType(OwnerType.SHOP.getValue());
        }

        Integer start = (pageNum - 1) * pageSize;

        // 查询查询分页数据
        List<StorageProduct> products = null;
        Long totalCount = null;
        if (StringUtils.isNotBlank(storageProduct.getColor())) {
            products = storageProductMapper.queryPageListByColor(storageProduct, start, pageSize);
            // 查询totalCount
            totalCount = storageProductMapper.queryPageCountByColor(storageProduct);
        } else {
            products = storageProductMapper.queryPageList(storageProduct, start, pageSize);
            // 查询totalCount
            totalCount = storageProductMapper.queryPageCount(storageProduct);
        }

        wrapperProduct(products, storageProduct);
        TableDataInfo pageList = new TableDataInfo(products, totalCount, pageNum, pageSize);

        // 为客户端库存管理处计算总金额
        if (storageProduct.getClient()) {
            pageList.setTotalMoney(getTotalMoney(storageProduct));
        }
        return new ServiceResponse<>(true, pageList, null);
    }

    /**
     * 为客户端库存管理处计算总金额
     * @param storageProduct
     * @return
     */
    private BigDecimal getTotalMoney(StorageProduct storageProduct) {
        BigDecimal totalMoney = new BigDecimal(0);
        List<StorageProduct> totalProducts = storageProductMapper.selectStorageProductList(storageProduct);
        if (!totalProducts.isEmpty()) {
            for (StorageProduct product : totalProducts) {
                // 查询商品列表
                StorageGoods goodsCondition = new StorageGoods();
                goodsCondition.setProductId(product.getId());
                goodsCondition.setCreateUserId(product.getCreateUserId());
                goodsCondition.setOwnerType(product.getOwnerType());
                if (org.apache.commons.lang3.StringUtils.isNotBlank(storageProduct.getColor())) {
                    goodsCondition.setColor(storageProduct.getColor());
                }
                List<StorageGoods> goodsList = storageGoodsMapper.selectStorageGoodsList(goodsCondition);
                for (StorageGoods goods : goodsList) {
                    // 进货价 * 数量
                    if (goods.getPurchasePrice() != null && goods.getStockNum() != null) {
                        BigDecimal result = goods.getPurchasePrice().multiply(new BigDecimal(goods.getStockNum()));
                        totalMoney = totalMoney.add(result);
                    }
                }
            }

        }
        return totalMoney;
    }

    /**
     * 查询代理商商品列表
     *
     * @param currentUser
     * @param storageProduct
     * @return
     */
    @Override
    public ServiceResponse<TableDataInfo> selectAgentProductList(StorageUser currentUser, StorageProduct storageProduct, Integer pageNum, Integer pageSize) {

        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSize == null) {
            pageSize = 10;
        }
        Integer start = (pageNum - 1) * pageSize;
        // 只查询在售的商品
        storageProduct.setStatus(ProductStatusType.IN_SELL.getValue());
        List<StorageProduct> products = null;
        Long totalCount = null;
        // 当前被采购代理商开放了那些品牌权限给下级那么下级就只能看到开发给他的品牌商品列表[如果当前采购方是直营店铺那么开放所有]
        if (RoleType.isAgent(currentUser.getRole())) {
            // 张皓采购上级张洪 张皓=currentUser.getId=3  张洪=storageProduct.getCreateUserId=7
            StorageUserAgent agent = storageUserAgentMapper.selectUserAgent(storageProduct.getCreateUserId(), currentUser.getId(), 1, OwnerType.AGENT.name());

            if (StringUtils.isNull(storageProduct.getBrandName()) && agent != null) {
                if (agent.getAcceptBrand() != null) {
                    List<String> acceptBrand = Arrays.asList(agent.getAcceptBrand().split(","));
                    storageProduct.setAcceptBrands(acceptBrand);
                    products = storageProductMapper.queryPageList(storageProduct, start, pageSize);
                    totalCount = storageProductMapper.queryPageCount(storageProduct);
                } else {
                    // 尚未开放任何品牌查询权限直接返回空数组
                    TableDataInfo pageList = new TableDataInfo(new ArrayList<>(), 0L, pageNum, pageSize);
                    return new ServiceResponse<>(true, pageList, null);
                }
            } else {
                products = storageProductMapper.queryPageList(storageProduct, start, pageSize);
                totalCount = storageProductMapper.queryPageCount(storageProduct);
            }
        } else {
            products = storageProductMapper.queryPageList(storageProduct, start, pageSize);
            totalCount = storageProductMapper.queryPageCount(storageProduct);
        }

        wrapperProduct(products, storageProduct);
        TableDataInfo pageList = new TableDataInfo(products, totalCount, pageNum, pageSize);
        return new ServiceResponse<>(true, pageList, null);
    }

    /**
     * 获取指定代理商商品的品牌集合
     *
     * @param storageUser
     * @param providerUserId
     * @return
     */
    @Override
    public ServiceResponse<List<String>> getSelectBrandValues(StorageUser storageUser, Long providerUserId) {
        StorageProduct product = new StorageProduct();
        if (providerUserId == null) {
            // 查询自己的库存和品牌列表
            Long userId = RoleType.getOperationUserId(storageUser.getRole(), storageUser.getId(), storageUser.getShopId());
            Integer ownerType = RoleType.getOwnerType(storageUser.getRole());
            product.setOwnerType(ownerType);
            product.setCreateUserId(userId);
        } else {
            // 查询指定代理商的品牌列表
            product.setOwnerType(OwnerType.AGENT.getValue());
            product.setCreateUserId(providerUserId);
        }

        List<StorageProduct> products = storageProductMapper.selectStorageProductList(product);

        // 去重获取品牌名称集合
        List<String> brands = products.stream().map(StorageProduct::getBrandName).distinct().collect(Collectors.toList());
        return new ServiceResponse<>(true, brands, null);
    }

    /**
     * 客户端库存管理title - 总金额、颜色、货号总数
     *
     * @param user
     * @return
     */
    /*@Override
    public ServiceResponse<Map<String, Object>> getStorageDetailInfo(StorageUser user) {
        // 查询库存列表
        Long userId = RoleType.getOperationUserId(user.getRole(), user.getId(), user.getShopId());
        Integer ownerType = RoleType.getOwnerType(user.getRole());

        StorageProduct condition = new StorageProduct();
        condition.setCreateUserId(userId);
        condition.setOwnerType(ownerType);
        List<StorageProduct> list = storageProductMapper.selectStorageProductList(condition);

        if (list.isEmpty()) {
            return new ServiceResponse<>(false, null, "商品库存为空");
        }

        Map<String, Object> resultMap = new HashMap<>();
        // 获取最终结果
        getStorageAmount(list, resultMap);

        return new ServiceResponse<>(true, resultMap, null);
    }*/

    @Override
    public ServiceResponse<AjaxResult> getProductShopSellDetail(StorageUser storageUser, String productSkuCode) {
        if (StringUtils.isBlank(productSkuCode)) {
            return new ServiceResponse<>(false, AjaxResult.error("产品skuCode不能为空"), "产品skuCode不能为空");
        }

        if (RoleType.isAgent(storageUser.getRole())) {
            List<ShopStorageDetail> details = new ArrayList<>();
            // 返回当前产品在当前代理商所辖店铺的库存信息
            StorageShop condition = new StorageShop();
            condition.setCreateUserId(storageUser.getId());
            List<StorageShop> shopLists = storageShopMapper.selectStorageShopList(condition);
            if (shopLists == null || shopLists.size() == 0) {
                return new ServiceResponse<>(true, AjaxResult.success(details), null);
            }

            for (StorageShop shop : shopLists) {
                StorageProduct product = storageProductMapper.selectStorageProduct(shop.getId(), OwnerType.SHOP.getValue(), productSkuCode);
                details.add(new ShopStorageDetail(shop, product));
            }

            return new ServiceResponse<>(true, AjaxResult.success(details), null);
        } else if (RoleType.isWorker(storageUser.getRole())) {
            // 查询返回当前用户所在店铺的的当前产品的销售列表
            StorageShopOrder condition = new StorageShopOrder();
            condition.setShopId(storageUser.getShopId());
            condition.setGoodsContent(productSkuCode);
            List<StorageShopOrder> orders = storageShopOrderMapper.selectStorageShopOrderList(condition);
            return new ServiceResponse<>(true, AjaxResult.success(orders), null);
        }
        return new ServiceResponse<>(false, AjaxResult.error("不支持的查询"), "不支持的查询");
    }

    @Override
    public ServiceResponse<AjaxResult> getProductShopSellDetailV2(StorageUser storageUser, String productSkuCode, Long shopId) {
        if (StringUtils.isBlank(productSkuCode)) {
            return new ServiceResponse<>(false, AjaxResult.error("产品skuCode不能为空"), "产品skuCode不能为空");
        } else if (shopId == null) {
            return new ServiceResponse<>(false, AjaxResult.error("shopId不能为空"), "shopId不能为空");
        }

        // 查询指定店铺的指定产品的销售列表
        StorageShopOrder condition = new StorageShopOrder();
        condition.setShopId(storageUser.getShopId());
        condition.setGoodsContent(productSkuCode);
        List<StorageShopOrder> orders = storageShopOrderMapper.selectStorageShopOrderList(condition);
        return new ServiceResponse<>(true, AjaxResult.success(orders), null);
    }

    @Override
    public AjaxResult updateProductStatus(StorageUser storageUser, StorageProduct product) {
        int result = storageProductMapper.updateStorageProduct(product);
        if (result == 1) {
            return AjaxResult.success("状态更新成功");
        }
        return AjaxResult.error("状态更新失败");
    }

    private void getStorageAmount(List<StorageProduct> list, Map<String, Object> resultMap) {
        BigDecimal amount = new BigDecimal(0);
        List<String> spuCode = new ArrayList<>();
        List<String> brands = new ArrayList<>();
        for (StorageProduct product : list) {
            spuCode.add(product.getProductSpuCode());
            brands.add(product.getBrandName());
            List<StorageGoods> goodsList = storageGoodsMapper.selectStorageGoodsByProductId(product.getId());
            if (goodsList.isEmpty()) {
                continue;
            }
            for (StorageGoods goods : goodsList) {
                // 进货价 * 数量
                if (goods.getPurchasePrice() != null && goods.getStockNum() != null) {
                    BigDecimal result = goods.getPurchasePrice().multiply(new BigDecimal(goods.getStockNum()));
                    amount = amount.add(result);
                }
            }
        }

        // 品牌去重
        brands = brands.stream().distinct().collect(Collectors.toList());

        resultMap.put("amountPrice", amount);
        resultMap.put("amountSpuCode", spuCode.size());
        resultMap.put("amountBrand", brands.size());
    }

    /**
     * 数据流转 产品
     *
     * @param products
     */
    private void wrapperProduct(List<StorageProduct> products, StorageProduct storageProduct) {
        for (StorageProduct product : products) {
            // 计算百分比
            String percent = NumerUtils.accuracy(product.getTotalGoodsNum() - product.getRealTimeGoodsNum(), product.getTotalGoodsNum(), 2);
            product.setPercent(percent);
            // 查询商品列表
            StorageGoods goodsCondition = new StorageGoods();
            goodsCondition.setProductId(product.getId());
            goodsCondition.setCreateUserId(product.getCreateUserId());
            goodsCondition.setOwnerType(product.getOwnerType());
            if (org.apache.commons.lang3.StringUtils.isNotBlank(storageProduct.getColor())) {
                goodsCondition.setColor(storageProduct.getColor());
            }
            List<StorageGoods> goodsList = storageGoodsMapper.selectStorageGoodsList(goodsCondition);
            // 查询对应产品的图片集合
            StorageImage imageCondition = new StorageImage();
            imageCondition.setLinkProductId(product.getId());
            List<StorageImage> images = storageImageMapper.selectStorageImageList(imageCondition);
            List<String> uuids = images.stream().map(StorageImage::getUuidName).collect(Collectors.toList());
            product.setImages(images);
            product.setUuids(uuids);
            product.setGoods(goodsList);
            GoodsConvertUtils.convert(product);
        }
    }

    /**
     * 修改产品
     *
     * @param products 产品信息
     * @return 结果
     */
    @Override
    public AjaxResult updateStorageProduct(StorageUser currentUser, String products) {
        if (org.apache.commons.lang3.StringUtils.isBlank(products)) {
            return AjaxResult.error("产品为空");
        }

        List<StorageProduct> productsArr = null;
        try {
            Gson gson = GsonUtil.getGson();
            productsArr = gson.fromJson(products, new TypeToken<List<StorageProduct>>() {
            }.getType());
        } catch (Exception ex) {
            logger.error("修改产品异常 error={}", ex);
            return AjaxResult.error("修改产品反序列化异常 products={}", products);
        }

        if (productsArr == null || productsArr.size() == 0) {
            return AjaxResult.error("商品列表为空");
        }

        Long userId = RoleType.getOperationUserId(currentUser.getRole(), currentUser.getId(), currentUser.getShopId());
        Integer ownerType = RoleType.getOwnerType(currentUser.getRole());

        for (StorageProduct product : productsArr) {
            product.setCreateUserId(userId);
            product.setOwnerType(ownerType);

            StorageProduct existProduct = storageProductMapper.selectStorageProduct(userId, ownerType, product.getProductSpuCode());
            if (existProduct == null) {
                // 新增
                storageProductMapper.insertStorageProduct(product);
                solutionImage(product);
                List<StorageGoods> goodsArr = product.getGoods();
                if (goodsArr != null && goodsArr.size() > 0) {
                    for (StorageGoods goods : goodsArr) {
                        goods.setProductId(product.getId());
                        goods.setOwnerType(ownerType);
                        goods.setCreateUserId(userId);
                        if (goods.getProductTime() == null) {
                            goods.setProductTime(new Date());
                        }
                        // 新增
                        storageGoodsMapper.insertStorageGoods(goods);
                    }
                }
            } else {
                // 编辑
                existProduct.setTotalGoodsNum(existProduct.getTotalGoodsNum() + product.getTotalGoodsNum());
                existProduct.setRealTimeGoodsNum(existProduct.getRealTimeGoodsNum() + product.getRealTimeGoodsNum());
                storageProductMapper.updateStorageProduct(existProduct);

                // 当前新增的单品和已经存在的单品进行比对
                List<StorageGoods> newGoods = product.getGoods();

                // 查询已存在单品列表
                StorageGoods goodsCondition = new StorageGoods();
                goodsCondition.setProductId(existProduct.getId());
                goodsCondition.setCreateUserId(existProduct.getCreateUserId());
                goodsCondition.setOwnerType(existProduct.getOwnerType());
                List<StorageGoods> oldGoods = storageGoodsMapper.selectStorageGoodsList(goodsCondition);

                for (StorageGoods newGood : newGoods) {
                    StorageGoods existGoods = null;
                    for (StorageGoods oldGood : oldGoods) {
                        if (checkPropertiesDetailMatch(oldGood, newGood)) {
                            existGoods = oldGood;
                        }
                    }
                    if (existGoods != null) {
                        // 已经存在的就增加库存数量
                        existGoods.setStockNum(existGoods.getStockNum() + newGood.getStockNum());
                        existGoods.setProductTime(new Date());
                        storageGoodsMapper.updateStorageGoods(existGoods);
                    } else {
                        // 不存在的就新增对应单品
                        newGood.setProductId(existProduct.getId());
                        newGood.setOwnerType(ownerType);
                        newGood.setCreateUserId(userId);
                        if (newGood.getProductTime() == null) {
                            newGood.setProductTime(new Date());
                        }
                        // 新增
                        storageGoodsMapper.insertStorageGoods(newGood);
                    }
                }
            }
        }
        return AjaxResult.success("操作成功", productsArr);
    }


    /**
     * 比对属性详情,进货价,批发价,零售价 是否相等
     * <p>
     * eg: [{"尺码":"35"}]
     *
     * @param existGoods
     * @param newGoods
     * @return
     */
    private boolean checkPropertiesDetailMatch(StorageGoods existGoods, StorageGoods newGoods) {
        if (org.apache.commons.lang3.StringUtils.isBlank(existGoods.getPropertiesDetail()) || org.apache.commons.lang3.StringUtils.isBlank(newGoods.getPropertiesDetail())) {
            return false;
        }

        JSONArray existArr = JSONArray.parseArray(existGoods.getPropertiesDetail());
        JSONArray newArr = JSONArray.parseArray(newGoods.getPropertiesDetail());
        if (existArr.size() != newArr.size()) {
            return false;
        } else if (!existArr.equals(newArr)) {
            return false;
        } else if (existGoods.getPurchasePrice().intValue() != newGoods.getPurchasePrice().intValue()) {
            return false;
        } else if (existGoods.getTradePrice().intValue() != newGoods.getTradePrice().intValue()) {
            return false;
        } else if (existGoods.getRetailPrice().intValue() != newGoods.getRetailPrice().intValue()) {
            return false;
        }
        return true;
    }

    /**
     * 关联图片处理
     *
     * @param product
     */
    private void solutionImage(StorageProduct product) {
        // 查询原来的已经关联上的图片集合
        StorageImage condition = new StorageImage();
        condition.setLinkProductId(product.getId());
        // 原有关联图片集合
        List<StorageImage> images = storageImageMapper.selectStorageImageList(condition);

        // 处理单品关联图片 - 最新关联集合
        List<String> uuids = product.getUuids();
        if (uuids == null || uuids.size() == 0) {
            // 清除所有关联的原有图片
            for (StorageImage image : images) {
                storageImageMapper.deleteStorageImageById(image.getId());
            }
        } else {
            // 对比差异，原有的不变，新增的将对应的productId以及goodsId更新到对应的记录，没有关联的就是删除
            List<String> oldUuids = images.stream().map(StorageImage::getUuidName).collect(Collectors.toList());
            for (String uuid : uuids) {
                if (oldUuids.contains(uuid)) {
                    continue;
                }
                storageImageMapper.updateStorageImageByUuid(product.getId(), uuid);
            }
            // 删除最新提交不包含的
            for (String oldUuid : oldUuids) {
                if (!uuids.contains(oldUuid)) {
                    storageImageMapper.deleteStorageImageByUuid(oldUuid);
                }
            }
        }
    }

    /**
     * 删除产品对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public AjaxResult deleteStorageProductByIds(StorageUser currentUser, String ids) {
        Long canOperationUserId = RoleType.getOperationUserId(currentUser.getRole(), currentUser.getId(), currentUser.getShopId());
        // 当前产品下面有商品不允许删除
        if (StringUtils.isBlank(ids)) {
            return AjaxResult.error("需要删除的产品id不能为空");
        } else if (canOperationUserId == null) {
            return AjaxResult.error("当前用户不具备该操做权限");
        }

        Integer ownerType = RoleType.getOwnerType(currentUser.getRole());
        String[] idArr = ids.split(",");
        for (String id : idArr) {
            StorageGoods goodsCondition = new StorageGoods();
            goodsCondition.setProductId(Long.parseLong(id));
            goodsCondition.setCreateUserId(canOperationUserId);
            goodsCondition.setOwnerType(ownerType);
            // 删除当前商品下的所有单品
            storageGoodsMapper.deleteStorageGoods(goodsCondition);
            storageProductMapper.deleteStorageProductById(Long.parseLong(id));
        }
        return AjaxResult.success();
    }

    /**
     * 修改商品(单品)
     *
     * @param storageGoods 商品信息
     * @return 结果
     */
    @Override
    public AjaxResult updateStorageGoods(StorageUser currentUser, StorageGoods storageGoods) {
        if (storageGoods != null && storageGoods.getId() == null) {
            Long operationUserId = RoleType.getOperationUserId(currentUser.getRole(), currentUser.getId(), currentUser.getShopId());
            storageGoods.setCreateUserId(operationUserId);
            storageGoods.setOwnerType(RoleType.getOwnerType(currentUser.getRole()));
            // 添加单品
            storageGoodsMapper.insertStorageGoods(storageGoods);
        } else {
            StorageGoods existGoods = storageGoodsMapper.selectStorageGoodsById(storageGoods.getId());
            if (storageGoods.getWarning() != null && storageGoods.getWarning() != existGoods.getWarning()) {
                // 更新对应单品的颜色相同的所有单品的预警值
                if (StringUtils.isNotBlank(storageGoods.getColor())) {
                    // 查询当前用户当前产品下的当前颜色的单品预警值修改
                    StorageGoods condition = new StorageGoods();
                    condition.setCreateUserId(existGoods.getCreateUserId());
                    condition.setProductId(existGoods.getProductId());
                    condition.setColor(storageGoods.getColor());
                    List<StorageGoods> goods = storageGoodsMapper.selectStorageGoodsList(condition);
                    for (StorageGoods good : goods) {
                        good.setWarning(storageGoods.getWarning());
                        storageGoodsMapper.updateStorageGoods(good);
                    }
                }
                storageGoodsMapper.updateStorageGoods(storageGoods);
            } else {
                // 更新商品
                storageGoodsMapper.updateStorageGoods(storageGoods);
            }
        }

        return AjaxResult.success(storageGoodsMapper.selectStorageGoodsById(storageGoods.getId()));
    }

    /**
     * 删除商品对象
     *
     * @param goodsIds 需要删除的数据ID
     * @return 结果
     */
    @Override
    public AjaxResult deleteStorageGoodsByIds(StorageUser currentUser, String goodsIds) {
        Long canOperationUserId = RoleType.getOperationUserId(currentUser.getRole(), currentUser.getId(), currentUser.getShopId());
        if (StringUtils.isBlank(goodsIds)) {
            return AjaxResult.error("需要删除的商品id不能为空");
        } else if (canOperationUserId == null) {
            return AjaxResult.error("当前用户不具备该操做权限");
        }
        Integer ownerType = RoleType.getOwnerType(currentUser.getRole());
        // 删除商品前先删除对应的商品 <--> 属性选项关联表的中间数据
        String[] goodsIdArr = goodsIds.split(",");
        for (String goodsId : goodsIdArr) {
            storageGoodsMapper.deleteStorageGoodsById(Long.parseLong(goodsId));
        }
        return AjaxResult.success();
    }

    /**
     * 上传图片
     *
     * @param currentUser
     * @param image
     * @return
     */
    @Override
    public AjaxResult uploadImage(StorageUser currentUser, StorageImage image) {
        // 代理商创建的就是代理商id，普通用户上传的就属于店铺
        Long canOperationId = RoleType.getOperationUserId(currentUser.getRole(), currentUser.getId(), currentUser.getShopId());
        if (canOperationId == null) {
            return AjaxResult.error("当前用户不具备上传权限");
        }
        image.setCreateUserId(canOperationId);
        storageImageMapper.insertStorageImage(image);
        return AjaxResult.success(image);
    }

}
